package com.bat.conf;

import cn.hutool.core.util.StrUtil;
import com.bat.util.TraceUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description:
 * @author: zhoupengfei
 * @create: 2019-10-12 10:40
 **/
@Slf4j
@Component
public class WebTraceRequestInterceptorConf  extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceid=request.getHeader(TraceUtil.traceid);
        if(StrUtil.isEmpty(traceid)){
            traceid = TraceUtil.getTraceId();
        }
        MDC.put(TraceUtil.traceid,traceid);

        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        MDC.remove(TraceUtil.traceid);
        TraceUtil.traceIdTreadLocal.remove();
        BaseController.futureList.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}